from gui.gui_base import GuiBase
from model.exception import ParkTokenFatalError, ParkTokenFindImageError
import sys
import os
import pyautogui

pyautogui.PAUSE = 0.3  # 每次调用后等待


class WindowGui(GuiBase):
    def __init__(self):
        super().__init__()
        self.hwnd = None
        self.search_time = 60
        self.confidence = 0.8
        self.grayscale = True

    def check_env(self):
        if not self.hwnd:
            raise ParkTokenFatalError("未设置窗口句柄")

    def click_image(self, image_path: str):
        """点击图片"""

        point = self.find_point_by_image(image_path)
        pyautogui.click(point)

    def click_images(self, image_paths):
        """点击图片"""

        point = None

        for image_path in image_paths:
            point = pyautogui.locateCenterOnScreen(
                image_path,
                confidence=self.confidence,
                grayscale=self.grayscale,
                minSearchTime=2,
            )

            if point:
                break
        
        if not point:
            raise ParkTokenFindImageError(image_paths)
        
        pyautogui.click(point)
        
    def click_point_by_scale(self, x, y):
        # 获取当前屏幕像素
        width, height = pyautogui.size()
        pyautogui.click(width * x, height * y)

    def hotkey(self, *args):
        """按键"""

        pyautogui.hotkey(*args)

    def set_hwnd(self, hwnd):
        self.hwnd = hwnd

    def find_point_by_image(self, image_path: str):
        """根据图片找到对应的坐标"""

        point = pyautogui.locateCenterOnScreen(
            image_path,
            confidence=self.confidence,
            grayscale=self.grayscale,
            minSearchTime=self.search_time,
        )

        if not point:
            raise ParkTokenFindImageError(image_path)

        return point

    def start(self):
        pass
